const { Blog, Op } = require("../model")

let get_fn = async (ctx, next) => {
    let a = ctx.request.body.text || ''
    if (a) {
        let list = await Blog.findAll({
            where: {
                [Op.or]: [
                    { id: isNaN(a) ? 0 : parseInt(a) },
                    { headline: a },
                    { abstract: a },
                    { content: a },
                    { classify: a },
                    { author: a },
                    { time: a }
                ]
            },
            order: ['id']
        })
        ctx.body = list
    } else {
        let list = await Blog.findAll({
            order: ['id']
        })
        ctx.body = list
    }
}

let post_fn = (ctx, next) => {
    let a = ctx.request.body
    Blog.create(a)
    ctx.body = 'abc'
}

let put_fn = async (ctx, next) => {
    let obj = ctx.request.body
    await Blog.update(obj, {
        where: {
            id: obj.id
        }
    })
    ctx.body = 'abc'
}

let delete_fn = async (ctx, next) => {
    let id = ctx.request.params.id
    await Blog.destroy({
        where: {
            id: id
        }
    })
    let list = await Blog.findAll({
        order: ['id']
    })
    ctx.body = list
}

module.exports = {
    "get /blog": get_fn,
    "post /blog": post_fn,
    "put /blog": put_fn,
    "delete /blog/:id": delete_fn
}